const Promise = require('bluebird')
const fly = require('flyio')
fly.config.timeout = 10000;
fly.config.baseURL = "https://api.bootcdn.cn/"

const Redis = require('ioredis')

const redis = new Redis({
    port: 6379, // Redis port
    host: '127.0.0.1', // Redis host
    family: 4, // 4 (IPv4) or 6 (IPv6)
    db: 0
})
class BootApi {
    constructor() {}
    /**
     * 获取列表
     */
    async serialize() {
        let cache_key = 'BOOT_API_LIST_SET'
        let keys = await redis.hkeys(cache_key)
        if (keys.length > 0) {
            console.log('等待下次缓存')
            return false
        } else {
            try {
                let res = await fly.get('libraries.min.json')
                let redis_hash_data = {}
                for (let item of res.data) {
                    redis_hash_data[item[0]] = JSON.stringify({
                        title: item[0],
                        desc: item[1],
                        star: item[2]
                    })
                    await redis.lpush('BOOT_APT_NAMES', item[0])
                }
                await redis.del(cache_key)
                await redis.hmset(cache_key, redis_hash_data)
                await redis.expire(cache_key, 86400)
            } catch (error) {
                console.log(error)
            }
            return true
        }
    }

    /**
     * 构建缓存
     */
    async buildcache() {
        let name = await redis.rpop('BOOT_APT_NAMES')
        if (!name) return false
        try {
            let res = await fly.get(`libraries/${name}.min.json`)
            await redis.hset('BOOT_API_DETAIL_SET', name, JSON.stringify(res.data))
        } catch (error) {
            await redis.lpush('BOOT_APT_NAMES', name)
        }
        return true
    }
}

module.exports = new BootApi()